package com.louis.iread.utils;

/**
 * Created by louis on 17-4-18.
 */

import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by joe on 03.09.15.
 */
public class Pagination {
    private boolean mIncludePad;
    private int mWidth;
    private int mHeight;
    private float mSpacingMult;
    private float mSpacingAdd;
    private  String mText;
    private TextPaint mPaint;
    private List<String> mPages;

    public Pagination(int pageW, int pageH, TextPaint paint, float spacingMult, float spacingAdd, boolean inclidePad) {
        this.mWidth = pageW;
        this.mHeight = pageH;
        this.mPaint = paint;
        this.mSpacingMult = spacingMult;
        this.mSpacingAdd = spacingAdd;
        mIncludePad = inclidePad;
    }

    public List<String>  SplitPages(String text)
    {
        this.mText = text;
        mPages = new ArrayList<>();
        layout();
        return mPages;
    }


    private void layout() {
        StaticLayout layout = new StaticLayout(mText, mPaint, mWidth, Layout.Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, mIncludePad);

        int lines = layout.getLineCount();
        String text = (String)layout.getText();
        int startOffset = 0;
        int height = mHeight;

        for (int i = 0; i < lines; i++) {
            if (height < layout.getLineBottom(i)) {
                // When the layout height has been exceeded
                addPage(text.substring(startOffset, layout.getLineStart(i)));
                startOffset = layout.getLineStart(i);
                height = layout.getLineTop(i) + mHeight;
            }

            if (i == lines - 1) {
                // Put the rest of the text into the last page
                addPage(text.substring(startOffset, layout.getLineEnd(i)));
                return;
            }
        }
    }

    private void addPage(String text) {
        mPages.add(text);
    }

    public int size() {
        return mPages.size();
    }

    public CharSequence get(int index) {
        return (index >= 0 && index < mPages.size()) ? mPages.get(index) : null;
    }
}